package com.hzqiuxm.tdddemo001.jinggame2;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Copyright © 2020年 tdd-demo-001. All rights reserved.
 *
 * @author 临江仙 hzqiuxm@163.com
 * 井字游戏实现类
 * @date 2020/7/3 9:47
 */
@Data
public class JingGameService2 {

    /**
     * 用来保存棋盘信息
     */
    private char[][] board = {{'\n','\n','\n'},{'\n','\n','\n'},{'\n','\n','\n'}};

    public static final int UP_BOUNDARY = 3;
    public static final int DOWN_BOUNDARY = 1;
    public static final int SIZE = 3;
    public char lastPlayer = ' ';
    boolean flag;
    private int turn = 0;

    @Autowired
    private TicTacService ticTacService;

    public void initGame() {
        ticTacService.clearAllTicTacs();
    }

    public String play(int xPoint, int yPoint){

        checkAxisX(xPoint);
        checkAxisY(yPoint);

        lastPlayer = nextPlayer();

        setBoard(new TicTacToeBean(++turn,xPoint,yPoint,lastPlayer));

        if(isWin()){
            return lastPlayer + " is winner";
        }else if(isDraw()){
            return "No Winner is Draw";
        }

        return "no winner";
    }

    /**
     * 是否平局
     * @return
     */
    private boolean isDraw() {

        for (int i = 0; i < SIZE;i++){
            for (int j = 0; j < SIZE; j++) {
                if (board[i][j] == '\n') {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 是否赢了
     * @return
     */
    private boolean isWin() {

        for (int i = 0; i < SIZE; i++){
            if(board[0][i] + board[1][i] + board[2][i] == lastPlayer*3){
                return true;
            }

            if(board[i][0] + board[i][1] + board[i][2] == lastPlayer*3){
                return true;
            }
        }

        if(board[0][0] + board[1][1] + board[2][2] == lastPlayer*3){
            return true;
        }

        if(board[0][2] + board[1][1] + board[2][0] == lastPlayer*3){
            return true;
        }

        return false;
    }

    /**
     * 下棋
     * @param ticTacToeBean
     */
    private void setBoard(TicTacToeBean ticTacToeBean) {
        if(board[ticTacToeBean.getX()-1][ticTacToeBean.getY()-1] != '\n'){
            throw new RuntimeException("位置冲突了,该位置已经有棋子了");
        }

        board[ticTacToeBean.getX()-1][ticTacToeBean.getY()-1] = ticTacToeBean.getPlayer();

        ticTacService.saveMove(ticTacToeBean);
    }

    private void checkAxisY(int yPoint) {
        if(yPoint > UP_BOUNDARY || yPoint < DOWN_BOUNDARY){
            throw new RuntimeException("Y轴越界了");
        }
    }

    private void checkAxisX(int xPoint) {
        if(xPoint > UP_BOUNDARY || xPoint < DOWN_BOUNDARY){
            throw new RuntimeException("X轴越界了");
        }
    }

    public char nextPlayer() {

        if(lastPlayer == 'W'){
            return 'B';
        }
        return 'W';
    }
}
